import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:flutter_demo_app/http/HttpController.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_demo_app/video_preview.dart';
// import './my_test.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';

class personalIndex extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => personalIndexState();
}

Future saveString(data_key, Map data) async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  sharedPreferences.setString(data_key, json.encode(data)); //存储对象
  print('存储成功');
}

class personalIndexState extends State<personalIndex> {
  var _storageString = new Map();
  var TestList = new List();
  var HighlightTimeList = new List();
  var userAvator;

  /**
   * 获取存在SharedPreferences中的数据
   */
  Future getString() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String uesrData = sharedPreferences.getString('user_data');
    Map<String, dynamic> temObjData = await json.decode(uesrData);
    setState(() {
      _storageString = temObjData;

      //获取作品列表
      findReadTestList();

      //获取高光时刻
      findHighlightTimeList();
    });
  }

  // 跳转到视频详情页
  goVideoPage() {
    //导航到新路由
    Navigator.push(context,
        new MaterialPageRoute(builder: (context) => new videoPreview()));
  }

  // 获取作品
  findReadTestList() {
    //定义变量
    Map<String, String> map = new Map();
    map["userId"] = _storageString["id"];
    map["id"] = _storageString["id"];
    map["page"] = '1';
    map["size"] = '3';
    print('_storageString["id"]');
    print(_storageString["id"]);

    HttpController.get(
        "https://www.bettermorph.com/micoservcice/user/personal/findReadTestList",
        (data) {
      if (data != null) {
        final body = json.decode(data.toString()); //接口返回的数据
        final feeds = body['obj']['content'];
        if (body['code'] == 0) {
          //更新变量值
          setState(() {
            TestList = feeds;
          });
        }
      }
    }, params: map);
  }

  //获取高光时刻
  findHighlightTimeList() {
    //定义变量
    Map<String, String> map = new Map();
    map["userId"] = _storageString["id"];
    map["id"] = _storageString["id"];
    map["page"] = '1';
    map["size"] = '3';
    print('_storageString["id"]');
    print(_storageString["id"]);

    HttpController.get(
        "https://www.bettermorph.com/micoservcice/user/personal/getHighlightTimeList",
        (data) {
      if (data != null) {
        final body = json.decode(data.toString()); //接口返回的数据
        final feeds = body['obj']['content'];
        if (body['code'] == 0) {
          //更新变量值
          setState(() {
            HighlightTimeList = feeds;
          });
        }
      }
    }, params: map);
  }

  @override
  void initState() {
    print('init state');
    super.initState();
    getString();
  }

  @override
  Widget build(BuildContext context) {

    //设置字体大小根据系统的“字体大小”辅助选项来进行缩放,默认为false
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

    // TODO: implement build
    //判断性别男女
    var finalGender = _storageString["sex"] == '0' ? '男' : '女';

    //判断用户头像
    if (_storageString["headUrl"] == null) {
      userAvator = CircleAvatar(
        child: Text("头像"),
        backgroundImage: AssetImage("assets/images/studentDefaultAvator.png"),
        radius: 50,
      );
    } else {
      userAvator = CircleAvatar(
        child: new CachedNetworkImage(
          imageUrl: '$_storageString["headUrl"]',
        ),
        backgroundImage: NetworkImage('${_storageString["headUrl"]}'),
        radius: 50,
      );
      // new CachedNetworkImage(imageUrl: '$_storageString["headUrl"].');
    }

//    print('TestListss');
//    print(TestList);

    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints viewportConstraints) {
        return SingleChildScrollView(
          child: ConstrainedBox(
            constraints: BoxConstraints(
              minHeight: viewportConstraints.maxHeight,
            ),
            child: Container(
              color: Colors.white,
              padding: const EdgeInsets.fromLTRB(20, 40, 0, 0),
              child: new Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Center(
                    child: userAvator,
                  ),
                  Container(
                    padding: const EdgeInsets.fromLTRB(0, 40, 0, 0),
                    child: new Row(
                      children: [
                        new Expanded(
                          child: new Text(
                            '个人信息',
                            style: TextStyle(color: Colors.red),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                    child: new Row(
                      children: [
                        new Expanded(
                          child: new Text('姓名：' + '${_storageString["cname"]}'),
                        ),
                        new Expanded(
                          child:
                              new Text('英文名：' + '${_storageString["ename"]}'),
                        ),
                        new Expanded(
                          // flex:1,
                          child: new Text('性别：' + '$finalGender'),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.fromLTRB(0, 5, 0, 0),
                    child: new Row(
                      children: [
                        new Expanded(
                          child: new Text('年龄：' + '${_storageString["age"]}岁'),
                        ),
                        new Expanded(
                          child: new Text('学员编号：' + '${_storageString["id"]}'),
                        ),
                        new Expanded(
                          // flex:1,
                          child: new Text(
                              '班级编号：' + '${_storageString["onlineClassNum"]}'),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.fromLTRB(0, 5, 0, 10),
                    child: new Row(
                      children: [
                        new Expanded(
                          child:
                              new Text('所属校区：' + '${_storageString["school"]}'),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                    child: new Row(
                      children: [
                        new Expanded(
                          child: new Text(
                            '我的作品',
                            style: TextStyle(color: Colors.red),
                          ),
                        ),
                      ],
                    ),
                  ),
                  buildGrid(TestList),
                  // listInfos(),
                  Container(
                    padding: const EdgeInsets.fromLTRB(0, 40, 0, 0),
                    child: new Row(
                      children: [
                        new Expanded(
                          child: new Text(
                            '高光时刻',
                            style: TextStyle(color: Colors.red),
                          ),
                        ),
                      ],
                    ),
                  ),
                buildGrid(HighlightTimeList),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  //  高光时刻和作品封装
  Widget buildGrid(data) {
    List<Widget> temArrayData = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in data) {
      if (item['name'] == null) {
        item['name'] = item['correlationId'];
      }
      temArrayData.add(new Container(
        child: new Column(children: <Widget>[
          Container(
            width: ScreenUtil.getInstance().setWidth(175),
            height: ScreenUtil.getInstance().setHeight(150),
            decoration: new BoxDecoration(
              color: Colors.white,
              border: new Border.all(width: 1.0, color: Colors.deepOrange),
              borderRadius: const BorderRadius.all(const Radius.circular(2.0)),
            ),
            alignment: Alignment.topLeft,
            margin: EdgeInsets.fromLTRB(0, 10, 20, 0),
            child: new Column(
              children: <Widget>[
                Expanded(
                  child: new Container(
                    width: ScreenUtil.getInstance().setWidth(175),
                    height: ScreenUtil.getInstance().setHeight(30),
                    decoration: new BoxDecoration(
                      color: Color(0xfffbebe8),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      '${item["name"]}',
                      style: TextStyle(
                        color: Color(0xffe8340c),
                        fontSize: ScreenUtil(allowFontScaling: true).setSp(24.0),
                      ),
                    ),
                  ),
                ),
                Stack(
                    // Aligment 的取值范围为 [-1, 1]，Stack 中心为 (0, 0)，
                    // 这里设置为 (-0.5, -0.5) 后，可以让控件对齐到 Container 的 1/4 处
                    alignment: const Alignment(0, 0),
                    children: <Widget>[
                      Image.network(
                        '${item["videoPicUrl"]}',
                        width: ScreenUtil.getInstance().setWidth(175),
                        height: ScreenUtil.getInstance().setHeight(120),
                      ),
                      IconButton(
                        icon: new Image.asset("assets/images/playIcon.png",
                            fit: BoxFit.cover),
                        onPressed: () {
                          //导航到新路由
                          Navigator.push(
                              context,
                              new MaterialPageRoute(
                                  builder: (context) => new videoPreview()));

                          saveString('current_video', item);
                        },
                      )
                    ])
              ],
            ),
          ),
          new Container(
            width: ScreenUtil.getInstance().setWidth(175),
            height: ScreenUtil.getInstance().setHeight(30),
            margin: const EdgeInsets.fromLTRB(0, 5, 0, 0),
            child: new Row(
              children: <Widget>[
                Expanded(
                  child: Text('${item["createDate"]}',
                      style: TextStyle(
                        color: Color(0xff000000),
                        fontSize: ScreenUtil(allowFontScaling: true).setSp(24),
                      )),
                )
              ],
            ),
          ),
        ]),
      ));
    }
    content = new Row(
        children: temArrayData //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
}
